package com.hxht.cmp.service.impl;

import com.hxht.cmp.common.Constants;
import com.hxht.cmp.entity.*;
import com.hxht.cmp.mapper.*;
import com.hxht.cmp.pojo.CourtCoordinate;
import com.hxht.cmp.pojo.SearchCriteria;
import com.hxht.cmp.service.CasePlanService;
import com.hxht.cmp.service.CaseReviewService;
import com.hxht.cmp.utils.BeanToMap;
import com.hxht.cmp.utils.CourtUidListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 案件排期相关
 */
@Service
public class CasePlanServiceImpl implements CasePlanService {
    final Logger logger = LoggerFactory.getLogger(CasePlanServiceImpl.class);
    @Autowired
    private PlanMapper planMapper;
    @Autowired
    private CaseMapper caseMapper;
    @Autowired
    private CourtRoomMapper courtRoomMapper;
    @Autowired
    private TrialMapper trialMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CaseReviewService caseReviewService;

    @Override
    public List<Map<String, Object>> selectListCasePlan(String courtUid, String date, String status) {
        //如果查询的是全局页面下的信息则对courtId进行处理
        List<Plan> planList = null;
        if (status.equals("1")) {
            Court nowCourt = Constants.COURT_MAP.get(courtUid);
            List<String> courtCodes = new ArrayList<>();
            if (!Objects.equals(courtUid, Constants.CENTRAL_COURT.getUid())) {
                for (Court court : Constants.COURT_LIST) {
                    if (Objects.equals(courtUid, court.getUid()) || Objects.equals(nowCourt.getUid(), court.getParentUid())) {
                        courtCodes.add(court.getUid());
                    }
                }
            }
            Map<String, Object> map = new HashMap<>();
            map.put("courtCodes", courtCodes);
            map.put("date", date);
            planList = planMapper.selectListAllCasePlan(map);
        } else {
            planList = planMapper.selectListCasePlan(courtUid, date);
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (!planList.isEmpty() && planList != null) {
            List<Case> caseList = caseMapper.selectCaseList(planList);
            for (Plan plan : planList) {
                for (Case aCase : caseList) {
                    if (plan.getCaseUid().equals(aCase.getUid())) {
                        Map<String, Object> map = new HashMap<>();
                        CourtRoom courtRoom = Constants.COURTROOM_MAP.get(plan.getCourtRoomUid());
                        map.put("courtUid", plan.getCourtUid());
                        map.put("name", aCase.getName());
                        map.put("accuse", aCase.getAccuse());
                        map.put("accused", aCase.getAccused());
                        map.put("accuse", aCase.getType());
                        map.put("courtroomName", courtRoom.getName());
                        map.put("courtroomUid", courtRoom.getUid());
                        map.put("caseUid", aCase.getUid());
                        map.put("planUid", plan.getUid());
                        map.put("startDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(plan.getStartDate()));
                        if (plan.getStatus() == 0) {
                            map.put("statusName", "排期");
                        } else {
                            map.put("statusName", "正在开庭");
                        }
                        mapList.add(map);
                    }
                }
            }
        }
        return mapList;
    }

    @Override
    public Map<String, Object> getCaseInfoByUid(String planUid) {
        Map<String, Object> map = new HashMap<>();
        //获取案件的plan信息
        Plan plan = new Plan();
        plan.setUid(planUid);
        Plan planOne = planMapper.selectOne(plan);
        if (planOne == null) {
            return map;
        }
        //基本案件信息
        Case ce = new Case();
        ce.setUid(planOne.getCaseUid());
        Case aCase = caseMapper.selectOne(ce);
        if (aCase == null) {
            return map;
        }
        //案件的所属法庭信息
        CourtRoom courtRoom = Constants.COURTROOM_MAP.get(planOne.getCourtRoomUid());
        //审判信息
        Trial trial = new Trial();
        trial.setPlanUid(planOne.getUid());
        Trial trialOne = trialMapper.selectOne(trial);
        //账户信息
        User user = new User();
        //获取法官信息
        user.setUid(planOne.getJudgeUserUid());
        User judgeUser = userMapper.selectOne(user);
        //获取书记员信息
        user.setUid(planOne.getSecretaryUserUid());
        User secretaryUser = userMapper.selectOne(user);
        Byte status = planOne.getStatus();
        if (0 == status) {
            map.put("statusName", "排期");
        } else if (1 == status) {
            map.put("statusName", "开庭");
        } else if (2 == status) {
            map.put("statusName", "休庭");
        } else if (3 == status) {
            map.put("statusName", "闭庭");
        } else if (4 == status) {
            map.put("statusName", "归档");
        } else {
            map.put("statusName", "未知");
        }
        String caseType = aCase.getCategory();
        List<Map<String, String>> allCaseType = caseReviewService.getAllCaseType();
        for (Map<String, String> type : allCaseType) {
            if (caseType.equals(type.get("uid"))) {
                map.put("casetypeName", type.get("name"));
            }
        }
        map.put("caseName", aCase.getName());
        map.put("archives", aCase.getArchives());
        if (courtRoom != null) {
            map.put("courtRoomName", courtRoom.getName());
        }
        //计划开庭时间 (格式化日期时确保不为null)
        if (null != planOne.getStartDate()) {
            map.put("planDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(planOne.getStartDate()));
        } else {
            map.put("planDate", "");
        }
        if (trialOne != null) {
            //案件实际开庭时间
            if (null != trialOne.getStartDate()) {
                map.put("startDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(trialOne.getStartDate()));
            } else {
                map.put("startDate", "");
            }
            //案件实际闭庭时间
            if (null != trialOne.getEndDate()) {
                map.put("endDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(trialOne.getEndDate()));
            } else {
                map.put("endDate", "");
            }
        }
        //原告
        map.put("accuse", aCase.getAccuse());
        //被告
        map.put("accused", aCase.getAccused());
        map.put("detail", aCase.getDetail());
        map.put("judgeUserUid", judgeUser.getUid());
        map.put("secretaryUserUid", secretaryUser.getUid());
        map.put("judgeName", judgeUser.getRealName());
        map.put("secretaryName", secretaryUser.getRealName());
        return map;
    }

    @Override
    public Map<String, Object> selectOnTimeByConditions(SearchCriteria searchCriteria, String onTimeType) {
        Map<String, Object> result = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置分页开始点
        searchCriteria.setPageStart((searchCriteria.getPage() - 1) * searchCriteria.getPageSize());
        //预设结果
        int count = -1;
        List<Map<String, Object>> temp = null;
        //设好边界和排序
        Integer min = null;
        Integer max = null;
        String order = "desc";
        List<Map<String, String>> allOnTimeType = caseReviewService.getAllOnTimeType();
        for (Map<String, String> one : allOnTimeType) {
            if (Objects.equals(one.get("uid"), onTimeType)) {
                if ("准点".equals(one.get("name"))) {
                    min = (0 - Constants.ON_TIME_BEFORE) - 1;
                    max = Constants.ON_TIME_AFTER + 1;
                } else if ("提前".equals(one.get("name"))) {
                    max = (0 - Constants.ON_TIME_BEFORE);
                } else {
                    min = Constants.ON_TIME_AFTER;
                    order = "asc";
                }
            }
        }
        if (Objects.equals(searchCriteria.getStatus(), "0")) {
            count = trialMapper.countOnTimeByConditions(searchCriteria, min, max);
            temp = trialMapper.selectOnTimeByConditions(searchCriteria, min, max, order);
        } else {
            if (!Objects.equals(searchCriteria.getCourtUid(), Constants.CENTRAL_COURT.getUid())) {
                List<String> courtUids = CourtUidListUtils.getChildrenCourtUidList(searchCriteria.getCourtUid());
                courtUids.add(searchCriteria.getCourtUid());
                searchCriteria.setCourtIdList(courtUids);
                searchCriteria.setCourtUid("");
            } else {
                searchCriteria.setCourtUid("");
            }
            count = trialMapper.countOnTimeByConditions(searchCriteria, min, max);
            temp = trialMapper.selectOnTimeByConditions(searchCriteria, min, max, order);
        }
        for (Map<String, Object> map : temp) {
//            CaseType caseType = Constants.CASE_TYPE_MAP.get(map.get("caseTypeUid"));
//            if (null != caseType) {
//                map.put("caseTypeName", caseType.getName());
//            }
//            map.put("lastUpdated", format.format(map.get("lastUpdated")));

            map.put("startDate", format.format(map.get("startDate")));
            map.put("courtroomName", Constants.COURTROOM_MAP.get(map.get("courtroomUid")).getName());
            if ((long) map.get("delaytime") < (0 - Constants.ON_TIME_BEFORE)) {
                map.put("onTimeType", "提前");
            } else if ((long) map.get("delaytime") > Constants.ON_TIME_AFTER) {
                map.put("onTimeType", "晚点");
            } else {
                map.put("onTimeType", "准点");
            }

        }
        result.put("count", count);
        result.put("data", temp);
        return result;
    }

    /**
     * 查询正在开庭数
     *
     * @param courtUid
     * @param status   0表示单个法院，1表示区域法院
     * @return
     */
    @Override
    public int getOpenNow(String courtUid, String today, String status) {
//        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Example example = new Example(Trial.class);
        Example.Criteria criteria = example.createCriteria();
        if ("0".equals(status)) {
            criteria.andEqualTo("courtUid", courtUid);
        } else {
            //如果是全局查询，若参数id与当前法院id相同则不要courtid的条件，不同则用in
            if (!Objects.equals(courtUid, Constants.CENTRAL_COURT.getUid())) {
                List<String> courtUids = CourtUidListUtils.getAllCourUidList(courtUid);
                criteria.andIn("courtUid", courtUids);
            }
        }
        criteria.andEqualTo("status", 1);
        criteria.andCondition("DATE_FORMAT(start_date, '%Y-%m-%d') = '" + today + "'");
        List<Trial> trials = trialMapper.selectByExample(example);
        return trials.size();
    }

    /**
     * 获取当前法院Uid及下级法院Uid的坐标
     *
     * @param courtUid
     * @return
     */
    @Override
    public List<Map<String, Object>> getCoordinate(String courtUid) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<String> courtUids = CourtUidListUtils.getChildrenCourtUidList(courtUid);
        courtUids.add(courtUid);
        for (CourtCoordinate coordinator : Constants.COURT_COORDINATE_LIST) {
            if (courtUids.contains(coordinator.getCourtUid())) {
                Map<String, Object> toMap = BeanToMap.beanToMap(coordinator);
                toMap.put("courtName", Constants.COURT_MAP.get(toMap.get("courtUid")).getName());
                result.add(toMap);
            }
        }
        return result;
    }
}
